<template>
  <div :class="'page-' + urlFrom">
    <div class="float-btn" :class="getShowBuyCard && !checkOwner && getCustomerId ? 'high-space' : ''">
      <ul style="position:relative">
        <li v-for="(item, index) in floatList" :key="index">
          <template v-if="urlFrom === 'home'">
            <button v-if="item.linkType === 1012 && enterpriseCustomerServiceAuthority === 1"
              :send-message-title="memberInfo.nickname + '的V客主页'" plain send-message-img="https://veekrayimg.joinsun.vip/images/share-s-picture.png"
              show-message-card="true" send-message-path="/pages/home/main" open-type="contact" class="contactBtn hidden-submit button-icon"
              :session-from="'7moor|'+ customerInfo.nickname + '|' + customerInfo.avatar +'|'+ customField"></button>
          </template>
          <template v-if="urlFrom === 'shopDetail'">
            <button v-if="item.linkType === 1012 && enterpriseCustomerServiceAuthority === 1"
              :send-message-title="goodsData.title" plain :send-message-img="goodsImg"
              show-message-card="true"
              :send-message-path="'/pages/shop/detail/main?memberId=' + getMemberId + '&goodsId=' + goodsData.goodsId + '&goodsType=' + goodsData.goodsType + '&shareMemberId=' + getCustomerId"
              open-type="contact" class="contactBtn hidden-submit button-icon" 
              :session-from="'7moor|'+ customerInfo.nickname + '|' + customerInfo.avatar +'|'+ customField"></button>
          </template>
          <div style="position:relative">
            <img v-if="item.imgUrl" :src="item.imgUrl" @click="linkTo(item)"
            class="width-58 height-58"/>
            <!-- 小B客服消息未读数 -->
            <span :class="unread['sellerUnread'] > 99 ? 'news-tag-style1': 'news-tag-style2'" v-if="item.linkType === 1011 && personalType === 0 && getCustomerId !== getMemberId && unread['sellerUnread'] > 0">{{unread.sellerUnread}}</span>
            <span :class="unread['buyerUnread'] > 99 ?'news-tag-style1' : 'news-tag-style2'" v-if="item.linkType === 1011 && personalType === 1 && unread['buyerUnread'] > 0">{{unread['buyerUnread']}}</span>
          </div>
        </li>
        <li
          v-if="!getCustomerId || !getPhone"
          style="width:100%;height:100%;position:absolute;top:0;left:0;z-index:1001;background:rgba(255,255,255,0)"
          @click="userInfo"></li>
      </ul>
    </div>
  </div>
</template>

<script>
  import { getMemberInfo } from '@/api/home'
  import { setCategoryInfo } from '@/utils/auth'
  import { getAuthority, listEnterpriseMessageConfig } from '@/api/common'
  export default {
    data() {
      return {
        memberInfo: {},
        customerInfo: {},
        goods: {},
        goodsImg: '',
        isGetUserInfo: false,
        linkList: {
          1001: '/pages/personal/coupon/coupon-center/main', // 领券中心
          1002: '/pages/contact-btn/main', // 微信客服
          1004: '/pages/shop/main', // 分类链接
          1005: '/pages/home/main', // 首页
          1006: '/pages/shop/main', // 分类
          1007: '/pages/shop/cart/main', // 购物车
          1008: '/pages/personal/main', // 个人中心
          1009: '/pages/home/content-center/main', // 内容中心
          1011: '/pages/personal/message/detail/main', // 小B客服
          1012: '/pages/contact-btn/main', // 企业客服
          1101: '/pages/home/second-custom/main', // 自定义页面
          1401: '/pages/home/live-list/main', // 直播列表
          1501: '/pages/home/default-seckill/main', // 限时秒杀
          2001: '/pages/shop/detail/main', // 商品详情
          4001: '/pages/home/content-center/content-detail/main' // 内容中心详情
        },
        personalType: '',
        customField: {}, // 企业客服自定义传参
        unread: {
          sellerUnread: 0, // 买家收到 卖家的消息(未读消息数)
          buyerUnread: 0 // 卖家收到 买家的消息(未读数)
        },
        messageIdsService: [],
        shopCustomerServiceAuthority: 1, // 小B客服增值功能 0关闭 1开启
        enterpriseCustomerServiceAuthority: 1 // 企业客服增值功能 0关闭 1开启
      }
    },
    props: {
      floatList: {
        type: Array,
        default: []
      },
      urlFrom: {
        type: String,
        default: ''
      },
      goodsData: {
        type: Object,
        default: {}
      }
    },
    onShow() {
      this.goodsImg = ''
      this.goodsData = {}
      this.$set(this.unread, 'sellerUnread', this.$pt.getStorageSync('imUnreadSeller') * 1 || this.getImUnreadSeller * 1)
      this.$set(this.unread, 'buyerUnread', this.$pt.getStorageSync('imUnreadBuyer') * 1 || this.getImUnreadBuyer * 1)
      this.data()
      this.messageService()
    },
    mounted() {
      this.goodsImg = ''
      this.goodsData = {}
      this.$set(this.unread, 'sellerUnread', this.$pt.getStorageSync('imUnreadSeller') * 1 || this.getImUnreadSeller * 1)
      this.$set(this.unread, 'buyerUnread', this.$pt.getStorageSync('imUnreadBuyer') * 1 || this.getImUnreadBuyer * 1)
      setTimeout(() => {
        this.data()
      }, 100)
      // 获取用户状态 买家：0   卖家：1
      this.personalType = this.$pt.getStorageSync('personalType')
      this.getAuthority()
      this.messageService()
    },
    watch: {
      getInMessage(val) {
        if (val === '1') {
          const that = this
          setTimeout(function() {
            that.$set(that.unread, 'sellerUnread', that.getImUnreadSeller * 1)
            that.$set(that.unread, 'buyerUnread', that.getImUnreadBuyer * 1)
          }, 2000)
        }
      }
    },
    methods: {
      data() {
        this.initMemberInfo()
        if (this.urlFrom === 'shopDetail') {
          if (this.goodsData.shareImageUrl) {
            this.goodsImg = this.goodsData.shareImageUrl
          }
          if (!this.goodsData.shareImageUrl && this.goodsData.images) {
            this.goodsImg = this.goodsData.images[0]
          }
        }
      },
      messageService() {
        this.messageIdsService = []
        const dataArr = ['1501', '1502']
        let dataStr = dataArr.toString()
        listEnterpriseMessageConfig({
          memberId: this.getMemberId,
          ascriptionTypes: dataStr
        })
          .then((response) => {
            if (response.isError) return
            response.data.forEach((item) => {
              if (item.miniMadeId) {
                this.messageIdsService.push(item.miniMadeId)
              }
            })
          })
          .catch(() => { })
      },
      // 小B客服 消息订阅
      serviceTo(item) {
        let that = this
        let rejectArr = []
        this.$pt.requestSubscribeMessage({
          tmplIds: that.messageIdsService,
          success: function(res) {
          // 成功
            Object.keys(res).forEach(key => {
              if (res[key] === 'reject') {
                rejectArr.push(key)
              }
            })
            if (rejectArr.length) {
              that.messageIdsService = rejectArr
              that.$utils.showToast({title: '请允许消息通知！'})
            } else {
              let cId = that.$pt.getStorageSync('customerId')
              let mId = that.$pt.getStorageSync('memberId')
              if (cId === mId) {
                that.$utils.showToast({
                  title: '不能与自己聊天'
                })
              } else {
                that.$pt.navigateTo({url: that.linkList[item.linkType] + '?memberId=' + that.getMemberId})
              }
            }
          },
          fail(err) {
          // 失败
            that.$utils.showToast({title: '消息订阅失败，' + err.errCode})
            console.error(err)
          }
        })
      },
      // 运营总后台 增值功能权限获取
      getAuthority() {
        getAuthority().then(res => {
          this.shopCustomerServiceAuthority = res.data.shopCustomerServiceAuthority
          this.enterpriseCustomerServiceAuthority = res.data.enterpriseCustomerServiceAuthority
        }).catch(err => {
          console.log(err)
        })
      },
      getCaption(obj) {
        let index = obj.lastIndexOf('=')
        obj = obj.substring(index + 1, obj.length)
        return obj
      },
      linkTo(item) {
        // if (item.linkType === 1001) {
        //   this.$pt.navigateTo({url: '/pages/personal/coupon/coupon-center/main'})
        // }
        if (item.linkType) {
          const linkType = Number(item.linkType)
          if (linkType === 1012 && this.enterpriseCustomerServiceAuthority === 0) {
            this.$utils.showToast({title: '链接已失效'})
            return
          }
          if (linkType === 1002) {
            this.$utils.showToast({title: '链接已失效'})
          }
          if (linkType === 1004) {
            this.$pt.removeStorageSync('categoryInfo')
            setCategoryInfo(this.$utils.getCaption(item.linkParams))
            this.$pt.switchTab({ url: this.linkList[item.linkType] })
            return
          }
          if (linkType === 1005 || linkType === 1006 || linkType === 1007 || linkType === 1008) {
            this.$pt.switchTab({ url: this.linkList[item.linkType] })
            return
          }
          if (linkType === 1011) {
            if (this.shopCustomerServiceAuthority === 0) {
              this.$utils.showToast({title: '链接已失效'})
            } else {
              this.serviceTo(item)
            }
            return
          }
          if (item.linkParams) {
            this.$pt.navigateTo({ url: this.linkList[item.linkType] + item.linkParams })
          } else {
            if (linkType === 1501) {
              this.$pt.navigateTo({ url: this.linkList[item.linkType] + '?enterpriseId=' + this.enterpriceId })
            } else {
              this.$pt.navigateTo({ url: this.linkList[item.linkType] })
            }
          }
        }
      },
      initMemberInfo() {
        getMemberInfo(this.getMemberId).then((response) => {
          if (response.isError) return
          this.memberInfo = response.data
        }).catch(() => {
        })
        getMemberInfo(this.getCustomerId).then((response) => {
          if (response.isError) return
          this.customerInfo = response.data
        }).catch(() => {
        })
      },
      userInfo() {
        this.$emit('userInfo', true)
      }
    }
  }
</script>

<style scoped lang="less">
  // 返回我的店铺按钮
  .page-home{
    .float-btn {
      bottom: 85px;
      &.high-space{
        bottom: 85px;
      }
    }
  }
  .float-btn {
    z-index: 100;
    position: fixed;
    bottom: 133px;
    right: 8px;
    width: 58px;
    height: 58px;
    text-align: center;
    &.high-space{
      bottom: 133px;
    }
    ul{
      li{
        position: relative;
        &:first-child{
          margin-bottom: 10px;
        }
        img{
          border-radius: 100px;
        }
        .contactBtn {
          background-color: transparent!important;
          position: absolute;
          width:100%;
          height:100%;
          left: 0;
          top: 0;
          z-index: 999;
          border-color: transparent!important;
          border: none!important;
        }
      }
    }
  }
      .news-tag-style1{
        position: absolute;
        font-size: 18rpx;
        background: #f00;
        color: #fff;
        border-radius: 5px;
        top: 0px;
        right: 4rpx;
        padding: 0px 4rpx;
      }
      .news-tag-style2 {
        position: absolute;
        font-size: 18rpx;
        background: #f00;
        color: #fff;
        border-radius: 50%;
        top: 0rpx;
        right: 4rpx;
        width: 30rpx;
        height: 30rpx;
        text-align: center;
      }
</style>
